<?php
// https://m.bhz360.com/index2.php?route=ssl/register
class ControllerSslRegister extends Controller {
    public function register() {
        $ret = array(
            'status' => false,
            'customerId' => 0,
        );
        $tel = intval($this->request->get['tel']);
        $pass = trim($this->request->get['pass']);
        $smsCode = intval($this->request->get['smsCode']);
        $recCode = trim($this->request->get['recCode']);
        $customerInShopId = trim($this->request->get['customerInShopId']);
        $now = date('Y-m-d H:i:s');
        $this->load->model('ssl/customer');
        $openId = $this->model_ssl_customer->getOpenIdByCustomerInShopId($customerInShopId);
        $ret['customerId'] = intval($this->model_ssl_customer->telCheck($tel));
        if (0 == $ret['customerId']) {
            //if ($this->model_ssl_customer->smsCodeCheck($tel, $smsCode)) {
            if (1) {
                $customerInfo = array(
                    'customer_group_id' => 1,
                    'fullname' => $tel,
                    'email' => $tel.'@bhz360.com',
                    'telephone' => $tel,
                    'fax' => $tel,
                    'password' => md5($pass),
                    'salt' => $this->getRandomCode(9),
                    'date_added' => $now,
                    'wx_mp_openid' => $openId,
                );
                $this->model_ssl_customer->addNew($customerInfo);
                $ret['info'] = $this->model_ssl_customer->bindCheck($openId);
                $ret['status'] = true;
            }else{
                $ret['message'] = '验证码错误';
            }
        }
        die(json_encode($ret));
    }

    public function sendCode() {
        $ret = array(
            'status' => false,
            'customerId' => 0,
        );

        $tel = intval($this->request->get['tel']);

        $this->load->model('ssl/customer');
        $ret['customerId'] = intval($this->model_ssl_customer->telCheck($tel));
        
        if (0 == $ret['customerId']) {
            $randomCode = $this->getRandomCode(6);
            $this->model_ssl_customer->saveSmsMobile($tel, $randomCode);
            $appId = $this->config->get('tianyi_appid');
            $appSecret = $this->config->get('tianyi_appsecret');
            $templateId = $this->config->get('tianyi_templateid');
            $params = array(
                'code' => $randomCode,
                'time' => 60
            );

			$danger = array(
				'method' => $sendMethod,
				'telphone' => trim($tel),
				'template_id' => $templateId,
				'date_added' => date ('Y-m-d H:i:s')
			);

			$this->load->model('tool/sms_log');

            //同一个用户发送验证码每天不能超过两次,每天发送验证码总条数不超过100的验证 by ypj at 2018.4.25 
            $this->load->model( 'account/smsmobile' );
            if($this->model_account_smsmobile->checkSendCodeNum($tel) ){
                die(json_encode($ret));
            }
            // end
            
            $res = $this->_sendCodeToTel($appId, $appSecret, $templateId, $tel, $params);

            //保存注册验证码的短信接口日志，便于排查异常   
            $log = array(
                'telphone' => trim($tel),
                'date_added' => date ('Y-m-d H:i:s'),
                'get_token_return' => $res['tokenReturn'],
                'template_id' => $templateId,
                'send_info' => json_encode($params),
                'send_return' => $res['sendReturn'],
                'return_status' => ('successful' == $res['returnStatus'])?1:0,
            );
            $this->model_tool_sms_log->saveData($log);
            //保存注册验证码的短信接口日志，便于排查异常
            $ret['status'] = true;
        }
        die(json_encode($ret));
    }

    public function getRandomCode($len) {
        $list = array ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
        $ret = '';
        while (strlen($ret) < $len) {
            $ret .= $list[array_rand($list, 1)];
        }
        return $ret;
    }

    protected function _sendCodeToTel($appId, $appSecret, $templateId, $tel, $params) {
        $ret = array();
        date_default_timezone_set('Asia/Shanghai');
        if(is_array($params)){
          $params = json_encode($params);
        }
        $timestamp = date('Y-m-d H:i:s');
        // 获取Accesss Token
        $url = "https://oauth.api.189.cn/emp/oauth2/v3/access_token";
        $postdata = 'app_id='.$appId.'&app_secret='.$appSecret.'&grant_type=client_credentials';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $ret['tokenReturn'] = curl_exec($ch);
        curl_close ($ch);
        $data = json_decode($ret['tokenReturn'], true);
        $access_token = $data['access_token'];
        if(!$access_token){
          $ret['returnStatus'] = "获取access_token失败: ".$data['res_message'];
          return $ret;
        }
        // 发送模板短信
        $url = "http://api.189.cn/v2/emp/templateSms/sendSms";
        $postdata = 'timestamp='.$timestamp.'&acceptor_tel='.$tel.'&template_id='.$templateId.'&template_param='.$params.'&app_id='.$appId.'&access_token='.$access_token;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $ret['sendReturn'] = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($ret['sendReturn'], true);
        if ($data ['res_code'] === 0) {
            $ret['returnStatus'] = 'successful';
        }else{
            $ret['returnStatus'] = $data['res_message'];
        }
        return $ret;
    }

}
